import React from 'react';
import styles from './hotQuestion.css';
import { Divider, Icon, Menu, message, Spin, Tooltip, Modal } from 'antd';
import { nice } from 'echarts/src/util/number';
import { connect } from 'dva';
import LabelModal from '@/pages/robotManagement/hotQuestion/labelModal';

const { confirm } = Modal;

class LabelList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isShowIconOption: false,
      menuList: [],
      selectedKeys: [],
      clickMenuInfo: null,
      spinning: false,
      selectIndex: null,
    };
  }

  componentDidMount() {
    this.getLabels('initial');
  }

  /**
   * 获取热点问题标签
   */
  getLabels = type => {
    const { dispatch, robotId } = this.props;
    const that = this;
    this.setState({ spinning: true, }, () => {
      dispatch({
        type: 'hotQuestion/fetchLabelList',
        payload: { robotId },
        callback: res => {
          console.log(res);
          that.setState({ spinning: false, menuList: res ? res : [], }, () => {
            if (res[0] && type && type === 'initial') {
              that.renderFirstLabelByInitial(res[0]);
            }
          });
        },
      });
    });
  };

  /**
   * 默认加载第一个标签的事件
   */
  renderFirstLabelByInitial = info => {
    this.setState({ selectedKeys: [info.id], selectIndex: 0, }, () => {
      this.getLabelInfo(info.id);
    });
  };

  /**
   * 显隐标签操作按钮
   */
  doIconOption = () => {
    const { isShowIconOption } = this.state;
    this.setState({ isShowIconOption: !isShowIconOption, });
  };

  /**
   *选择标签
   */
  menuSelect = item => {
    this.setState({ selectedKeys: [item.item.props.id], selectIndex: item.item.props.index, }, () => {
      this.getLabelInfo(item.item.props.id);
    });
  };

  /**
   * 获取标签详情
   */
  getLabelInfo = id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'hotQuestion/getLabelInfoById',
      payload: { id },
      callback: res => {
        this.props.getCurrentLabelInfo(res);
        this.setState({ clickMenuInfo: res, });
      },
    });
  };

  /**
   * 上移/下移
   */
  upOrDownLabel = type => {
    const { dispatch } = this.props;
    let { selectIndex, menuList, selectedKeys } = this.state;
    if (selectIndex === 0 && type === 0) {
      return message.error('该标签已经是第一位，无法上移');
    };
    if (selectIndex === menuList.length - 1 && type === 1) {
      return message.error('该标签已经是最后一位，无法下移');
    };
    let orderIndex = '';
    let order = '';
    switch (type) {
      case 0:
        orderIndex = parseInt(selectIndex) - 1;
        order = menuList[orderIndex].labelOrder;
        selectIndex = orderIndex;
        break;
      case 1:
        orderIndex = parseInt(selectIndex) + 1;
        order = menuList[orderIndex].labelOrder;
        selectIndex = orderIndex;
        break;
    }
    dispatch({
      type: 'hotQuestion/doUpOrDownLabel',
      payload: { id: selectedKeys[0], order },
      callback: res => {
        message.info(res.message);
        this.setState({ selectIndex, }, () => {
          this.getLabels();
        });
      },
    });
  };

  /**
   * 删除标签
   */
  removeLabel = () => {
    const { selectedKeys } = this.state;
    const that = this;
    confirm({
      title: '确定要删除该标签吗？',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        const { dispatch } = that.props;
        dispatch({
          type: 'hotQuestion/doRemoveLabel',
          payload: { id: selectedKeys[0] },
          callback: res => {
            message.info(res.message);
            //删除标签后 初始化标签树 且默认选中第一个标签
            that.getLabels('initial');
          },
        });
      },
      onCancel() { },
    });
  };

  /**
   * 打开新增/编辑modal
   */
  openLabelModal = type => {
    const { clickMenuInfo } = this.state;
    switch (type) {
      case 'edit':
        this.LabelModal.initModal(clickMenuInfo);
        break;
      case 'add':
        this.LabelModal.initModal();
    }
  };

  /**
   * 修改标签
   */
  editLabel = (values, id) => {
    const { dispatch, robotId } = this.props;
    values.robotId = robotId;
    values.id = id;
    dispatch({
      type: 'hotQuestion/doEditLabel',
      payload: values,
      callback: res => {
        message.info(res.message);
        this.LabelModal.cancelModal();
        this.getLabels();
        this.getLabelInfo(id);
      },
    });
  };

  /**
   * 新增标签
   */
  addLabel = values => {
    const { dispatch, robotId } = this.props;
    values.robotId = robotId;
    dispatch({
      type: 'hotQuestion/doAddLabel',
      payload: values,
      callback: res => {
        message.info(res.message);
        this.LabelModal.cancelModal();
        this.getLabels();
      },
    });
  };

  render() {
    const { isShowIconOption, menuList, selectedKeys, spinning } = this.state;
    return (
      <div>
        <div>
          {isShowIconOption ? (
            <div className={styles.iconOptions}>
              <Tooltip title="上移">
                <Icon
                  type="up-circle"
                  className={selectedKeys.length > 0 ? styles.icons : styles.iconsDisabled}
                  onClick={() => this.upOrDownLabel(0)}
                />
              </Tooltip>
              <Tooltip title="下移">
                <Icon
                  type="down-circle"
                  className={selectedKeys.length > 0 ? styles.icons : styles.iconsDisabled}
                  onClick={() => this.upOrDownLabel(1)}
                />
              </Tooltip>
              <Tooltip title="删除">
                <Icon
                  type="delete"
                  className={selectedKeys.length > 0 ? styles.icons : styles.iconsDisabled}
                  onClick={this.removeLabel}
                />
              </Tooltip>
              <Tooltip title="修改">
                <Icon
                  type="form"
                  className={selectedKeys.length > 0 ? styles.icons : styles.iconsDisabled}
                  onClick={() => this.openLabelModal('edit')}
                />
              </Tooltip>
              <Tooltip title="新增">
                <Icon
                  type="plus-circle"
                  className={styles.icons}
                  onClick={() => this.openLabelModal('add')}
                />
              </Tooltip>
              <Tooltip title="返回">
                <Icon type="right" className={styles.icons} onClick={this.doIconOption} />
              </Tooltip>
            </div>
          ) : (
            <div style={{ overflow: 'hidden' }}>
              <div className={styles.menuTitle}>标签</div>
              <div className={styles.menuOption}>
                <Icon type="menu-fold" onClick={this.doIconOption} />
              </div>
            </div>
          )}
        </div>
        <div>
          <Spin spinning={spinning}>
            <Menu
              theme="light"
              mode="inline"
              onClick={item => this.menuSelect(item)}
              selectedKeys={selectedKeys}
            >
              {menuList.map((item, index) => {
                return (
                  <Menu.Item key={item.id} id={item.id} name={item.name} index={index}>
                    {item.name}
                  </Menu.Item>
                );
              })}
            </Menu>
          </Spin>
        </div>
        <LabelModal
          onRef={ref => (this.LabelModal = ref)}
          editLabel={this.editLabel}
          addLabel={this.addLabel}
        />
      </div>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(LabelList);
